import io

from myhttp import HttpResponse
import config
import re


class TemplateDoesNotExist(BaseException):
    pass


class Template:
    def __init__(self, template):
        try:
            with open(config.template_dir + "/" + template, "r") as fp:
                fp.seek(0, io.SEEK_END)
                file_size = fp.tell()
                fp.seek(0, io.SEEK_SET)
                self.content = fp.read(file_size)
        except:
            raise TemplateDoesNotExist

    def render(self, context):
        content = self.content

        var_regex = "\{\{\\s*[a-zA-Z0-9\_\.]+\\s*\}\}"
        for _var in re.findall(var_regex, content):
            m = re.match("\{\{\\s*(?P<name>[a-zA-Z0-9\_\.]+)\\s*\}\}", _var)
            if not m:
                continue

            var = m.group("name")
            _strs = var.split(".")
            if _strs[0] not in context:
                content = content.replace(_var, "")
            else:
                if len(_strs) == 1:
                    value = str(context.get(var))
                elif len(_strs) > 1:
                    obj = context.get(_strs[0])
                    attr = obj
                    for v in _strs[1:]:
                        attr = getattr(attr, v)

                    if callable(attr):
                        value = attr()
                    else:
                        value = str(attr)
                content = content.replace(_var, value)
        return content


class TemplateResponse(HttpResponse):
    def __init__(self, template, context={}):
        super().__init__(status=200)
        t = Template(template)
        self.body = t.render(context)


if __name__ == "__main__":
    class User:
        def __init__(self):
            self.name = "bob"


    user = User()
    template = Template("index.html")
    print(template.render({"name": "jim", "age": 10, "user": user}))
